<template>
  <div id="pageNodeList">
    <v-container grid-list-xl fluid>
      <v-layout row warp>
        <v-flex xs12>
          <v-container>
            <v-text-field
              v-model="search"
              id="search"
              key="search"
              label="搜索"
              append-icon="search"
              clearable
              hide-details
              single-line
              solo
              light
              @keyup.enter="init"
            />
          </v-container>
          <v-card class="mb-4">
            <v-toolbar color="primary lighten-1" dark flat dense cad>
              <v-toolbar-title class="subheading">节点管理</v-toolbar-title>
              <v-spacer></v-spacer>
              <v-dialog v-model="dialog" persistent max-width="600px">
                <v-btn slot="activator" flat dark>
                  <v-icon>add</v-icon>&nbsp;新建
                </v-btn>
                <v-card>
                  <v-card-title>
                    <span class="headline">{{ formTitle }}</span>
                  </v-card-title>
                  <v-card-text>
                    <v-container grid-list-md>
                      <v-form>
                        <v-layout wrap>
                          <v-flex xs12 sm6>
                            <v-text-field
                              name="title"
                              label="节点标题*"
                              v-validate="'required'"
                              data-vv-as="节点名称"
                              data-vv-validate-on="blur"
                              :error="errors.has('title')"
                              :error-messages="errors.collect('title')"
                              v-model="editedItem.title"
                            ></v-text-field>
                          </v-flex>
                          <v-flex xs12 sm6>
                            <v-select
                              name="node_id"
                              :items="parentNodes"
                              item-text="title"
                              item-value="id"
                              label="父级菜单"
                              v-model="editedItem.node_id"
                              clearable
                            ></v-select>
                          </v-flex>
                          <v-flex xs12>
                            <v-textarea
                              name="description"
                              label="描述"
                              auto-grow
                              v-model="editedItem.description"
                            ></v-textarea>
                          </v-flex>
                          <v-flex xs12>
                            <v-text-field name="icon" label="图标" v-model="editedItem.icon"></v-text-field>
                          </v-flex>
                          <v-flex xs12>
                            <v-text-field name="banner" label="图片" v-model="editedItem.banner"></v-text-field>
                          </v-flex>
                          <v-flex xs12 sm6>
                            <v-btn outline color="blue" class="white--text ma-0" type="file">
                              <v-icon left dark>cloud_upload</v-icon>点击上传
                            </v-btn>
                          </v-flex>
                          <v-flex xs12>
                            <v-text-field name="order" label="排序" v-model="editedItem.order"></v-text-field>
                          </v-flex>
                          <v-flex xs12 sm6>
                            <v-switch
                              name="status"
                              :label="(editedItem.status ? `显示`: `隐藏`) + `节点`"
                              v-model="editedItem.status"
                            ></v-switch>
                          </v-flex>
                        </v-layout>
                      </v-form>
                    </v-container>
                  </v-card-text>
                  <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="blue darken-1" flat @click="close">取消</v-btn>
                    <v-btn color="blue darken-1" flat @click="save">保存</v-btn>
                  </v-card-actions>
                </v-card>
              </v-dialog>
            </v-toolbar>
            <v-divider></v-divider>
            <v-card-text></v-card-text>
          </v-card>
        </v-flex>
      </v-layout>
    </v-container>
  </div>
</template>
<script>
import _ from 'lodash'
import { getAllNodes, createNode, updateNode, deleteNode } from '@/api/resource/nodes'
import Toast from '@/plugins/toast'
export default {
  name: 'node-list',
  components: {

  },
  data: () => ({
    headers: [
      { text: 'ID', value: 'id' },
      { text: '标题', value: 'title' },
      { text: '排序', value: 'order' },
      { text: '状态', value: 'status' },
      { text: '操作', value: 'action', sortable: false }
    ],
    dialog: false,
    loading: true,
    search: '',
    totalNodes: 0,
    nodes: [],
    selected: [],
    pagination: {},
    editedIndex: -1,
    editedItem: {
      id: 0,
      node_id: 0,
      title: '',
      icon: '',
      banner: '',
      description: '',
      order: 999,
      status: 1
    },
    defaultItem: {
      id: 0,
      node_id: 0,
      title: '',
      icon: '',
      banner: '',
      description: '',
      order: 999,
      status: 1
    }
  }),
  computed: {
    formTitle () {
      return this.editedIndex === -1 ? '新建菜单' : '编辑菜单'
    },
    parentNodes () {
      return _.filter(this.nodes, (o) => {
        return o.node_id === 0
      })
    }
  },
  watch: {
    dialog (val) {
      val || this.close()
    }
  },
  methods: {
    toggleAll () {
      let _this = this
      if (_this.selected.length) _this.selected = []
      else _this.selected = _this.nodes.slice()
    },
    toggleReverse (items) {
      this.selected = _.difference(items, this.selected)
    },
    changeSort (column) {
      let _this = this
      if (_this.pagination.sortBy === column) {
        _this.pagination.descending = !_this.pagination.descending
      } else {
        _this.pagination.sortBy = column
        _this.pagination.descending = false
      }
    },
    init () {
      let _this = this
      let params = {
        perPage: _this.pagination.rowsPerPage,
        page: _this.pagination.page,
        sortBy: ((_this.pagination.sortBy) ? _this.pagination.sortBy : `id`) + `,` + ((_this.pagination.descending === true) ? `desc` : `asc`)
      }
      if (_this.search) {
        params.search = _this.search
      }
      _this.loading = true
      getAllNodes({ 'params': params }).then(res => {
        _this.nodes = res.data
        _this.totalNodes = res.meta.pagination.total
        _this.loading = false
      })
    },
    editItem (item) {
      let _this = this
      _this.editedIndex = _this.nodes.indexOf(item)
      _this.editedItem = Object.assign({}, item)
      _this.dialog = true
    },
    deleteItem (item) {
      let _this = this
      const index = _this.nodes.indexOf(item)
      _this.$swal.fire({
        title: '你确定删除吗？',
        text: '删除后无法恢复!',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).then(result => {
        if (result.value) {
          deleteNode(item.id).then(res => {
            _this.nodes.splice(index, 1)
            _this.$swal.fire(
              '已删除!',
              '选中项已被删除.',
              'success'
            )
          })
        }
      })
    },
    deleteSelected (items) {
      let _this = this
      let ids = []
      if (_this.selected.length === 0) {
        Toast.error({ msg: '请选择' })
        return false
      }
      _(_this.selected).forEach(function (value) {
        ids.push(value.id)
      })
      ids = ids.join()
      _this.$swal.fire({
        title: '你确定删除吗？',
        text: '删除后无法恢复!',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).then(result => {
        if (result.value) {
          deleteNode(ids).then(res => {
            _this.nodes = _.difference(_this.nodes, _this.selected)
            _this.$swal.fire(
              '已删除!',
              '选中项已被删除.',
              'success'
            )
          })
        }
      })
    },
    save () {
      let _this = this
      let index = _this.editedIndex
      let item = _this.editedItem
      _this.$validator.validateAll().then(result => {
        if (result) {
          if (index > -1) {
            updateNode(item.id, item).then(res => {
              Object.assign(_this.nodes[index], item)
              Toast.success({ msg: '修改成功' })
            })
          } else {
            createNode(item).then(res => {
              _this.nodes.push(res.data)
              Toast.success({ msg: '添加成功' })
            })
          }
          _this.close()
        }
      })
    },
    close () {
      let _this = this
      _this.dialog = false
      _this.editedItem = Object.assign({}, _this.defaultItem)
      _this.editedIndex = -1
    }
  }
}
</script>
